package com.shop.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.entity.pojo.*;
import com.shop.user.mapper.*;
import com.shop.user.service.WaresService;
import com.shop.utils.common.enums.Message;
import com.shop.utils.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;


@Service
@Slf4j
public class WaresServiceImpl extends ServiceImpl<WaresMapper, Wares> implements WaresService{

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Result<List<Wares>> getAllWares() {
        log.info("用户-获取所有商品");
        long start = System.currentTimeMillis();
        String key=Message.WeChat_Key_Wares_All;
        List<Wares> check = (List<Wares>) redisTemplate.opsForValue().get(key);
        if (check!=null&&check.size()>0) {
            log.info("浏览缓存");
            long end = System.currentTimeMillis();
            log.info("用户从缓存获取所有商品进程完成，总耗时:{}",(end-start));
            return Result.okResult(check);
        }
        log.info("浏览数据库");
        List<Wares> list = list(Wrappers.<Wares>lambdaQuery().eq(Wares::getState, Message.Put));
        redisTemplate.opsForValue().set(key,list);
        long end = System.currentTimeMillis();
        log.info("用户从数据库获取所有商品进程完成，总耗时:{}",(end-start));
        return Result.okResult(list);
    }

    @Override
    public Result<List<Wares>> getBrandsWares(Long brandsId) {
        long start = System.currentTimeMillis();
        log.info("用户-分类商品展示");
        String key=Message.WeChat_Key_Brands+brandsId;
        List<Wares> check = (List<Wares>) redisTemplate.opsForValue().get(key);
        if (check!=null&&check.size()>0) {
            log.info("浏览缓存");
            long end = System.currentTimeMillis();
            log.info("用户从缓存获取分类后商品进程完成，总耗时:{}",(end-start));
            return Result.okResult(check);
        }
        log.info("浏览数据库");
        List<Wares> list = list(Wrappers.<Wares>lambdaQuery().eq(Wares::getBrandsId, brandsId).eq(Wares::getState, Message.Put));
        redisTemplate.opsForValue().set(key,list);
        long end = System.currentTimeMillis();
        log.info("用户从数据库获取分类后商品进程完成，总耗时:{}",(end-start));

        return Result.okResult(list);
    }
}
